<template>
	<div class="login">
		<el-card class="login_box" :body-style="{ padding: '0px' }">
			<el-form
				ref="loginForm"
				:model="loginUser"
				status-icon
				:rules="rules"
				class="loginForm"
			>
				<el-form-item label="邮箱" prop="email">
					<el-input
						v-model="loginUser.email"
						placeholder="请输入邮箱"
					/>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input
						type="password"
						v-model="loginUser.password"
						placeholder="请输入密码"
					/>
				</el-form-item>

				<el-form-item class="last-fitem">
					<el-button
						type="primary"
						class="submit_btn"
						@click="submitForm()"
						>登录</el-button
					>
				</el-form-item>
			</el-form>
		</el-card>
	</div>
</template>

<script>
import { reactive, ref, toRefs } from "vue";
import jwt_decode from "jwt-decode";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { login } from "../network/login";

import { ElMessage } from "element-plus";

export default {
	name: "Login",
	setup() {
		// vuex
		const store = useStore();
		// router
		const router = useRouter();
		// $ref
		const loginForm = ref(null);
		// 数据模型
		const data = reactive({
			loginUser: {
				email: "",
				password: "",
			},
		});
		// elementui表单验证
		const rules = reactive({
			email: [
				{
					type: "email",
					required: true,
					message: "邮箱格式不正确",
					trigger: "blur",
				},
			],
			password: [
				{ required: true, message: "密码不能为空", trigger: "blur" },
				{
					min: 6,
					max: 30,
					message: "长度在6-30个字符之间",
					trigger: "blur",
				},
			],
		});

		// 登录
		const submitForm = (formEl = loginForm.value) => {
			if (!formEl) return;
			formEl.validate((valid) => {
				if (valid) {
					login(data.loginUser).then((res) => {
						//token
						const { token } = res.data;
						// 存储到localStorage
						localStorage.setItem("blog_publish_token", token);

						// 登录成功
						ElMessage.success("登录成功");
						// router 跳转到首页
						setTimeout(() => {
							router.push({ path: "/home" });
						}, 500);
					});
				}
			});
		};

		return {
			loginForm,
			...toRefs(data),
			rules,
			submitForm,
		};
	},
};
</script>

<style lang="scss" scoped>
.login {
	width: 100%;
	height: 100vh;
	position: relative;
	background: #000;
	opacity: 0.9;
	.login_box {
		position: absolute;
		top: 50%;
		left: 50%;
		z-index: 2;
		transform: translate(-50%, -50%);
		.loginForm {
			width: 300px;
			background-color: #fff;
			padding: 20px;
			box-sizing: border-box;
			border-radius: 5px;
			box-shadow: 0px 5px 10px #cccc;
			.last-fitem {
				margin-bottom: 0;
			}
			.submit_btn {
				width: 100%;
			}
		}
	}
}
</style>
